package storage

import (
	"context"
	"fmt"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"io"
	"log"
)

func NewMinio(endpoint, accessKeyID, secretAccessKey string) *Minio {
	client, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: true,
	})
	if err != nil {
		log.Fatalf("创建MinIO客户端失败： %v", err)
	}
	return &Minio{client: client}
}

type Minio struct {
	client *minio.Client
}

func (m *Minio) Upload(bucketName, objectName string, reader io.Reader) error {
	_, err := m.client.PutObject(context.Background(), bucketName, objectName, reader, -1, minio.PutObjectOptions{})
	if err != nil {
		return fmt.Errorf("上传文件失败： %v", err)
	}
	return nil
}

func (m *Minio) Download(bucketName, objectName string) error {
	err := m.client.FGetObject(context.Background(), bucketName, objectName, "writer", minio.GetObjectOptions{})
	if err != nil {
		return fmt.Errorf("下载文件失败： %v", err)
	}
	return nil
}
